package com.ac.api.production_order.controller;

import com.ac.api.process_task.entity.ProcessTask;
import com.ac.api.production_order.entity.noEquitmentException;
import com.ac.utils.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.RequestMapping;
import com.base.annotation.SysLog;
import org.springframework.web.bind.annotation.RestController;
import com.base.helper.BaseController;
import com.base.helper.Result;
import com.ac.api.production_order.entity.ProductionOrder;
import com.ac.api.production_order.service.ProductionOrderService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 生产订单主表 前端控制器
 * </p>
 *
 * @author dc
 * @since 2025-06-11
 */
@Api(tags = "ProductionOrder")
@RestController
@RequestMapping("/productionOrder")
public class ProductionOrderController extends BaseController {

        private static final Logger       LOG = LoggerFactory.getLogger(ProductionOrderController.class);
        @Autowired
        private              ProductionOrderService entityService;

        @SysLog(action = "findByPage", value = "分页查询订单")
        @ApiOperation(value = "分页查询订单", notes = "分页查询订单")
        @GetMapping("/findByPage")
        @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
        public Result<IPage<ProductionOrder>> findByPage(final ProductionOrder example, final Page page) {
            IPage<ProductionOrder>        records    = entityService.page(example,page);
            return new Result(true, records);
        }

        @SysLog(action = "delete", value = "删除订单")
        @ApiOperation(value = "删除订单")
        @DeleteMapping("/delete/{id}")
        @ApiImplicitParam(name = "id", value = "订单ID", required = true, paramType = "path")
        public Result delete(@PathVariable Integer id) {
            try {
                entityService.remove(new QueryWrapper<ProductionOrder>().eq("order_id", id));
                return new Result(true, "成功删除订单", null);
            } catch (DataIntegrityViolationException e) {
                LOG.error("删除订单失败", e);
                return new Result(false, "删除订单失败", "该订单不能删除，存在其他关联数据");
            } catch (Exception e) {
                LOG.error("删除订单失败", e);
                return new Result(false, "删除订单失败", e.getMessage());
            }
        }

        @SysLog(action = "one", value = "查询单个订单")
        @ApiOperation(value = "查询单个订单")
        @GetMapping("/one/{id}")
        public Result one(@PathVariable Integer id) {
            try {
                ProductionOrder entity = entityService.getById(id);
                return new Result(true, entity);
            } catch (Exception e) {
                LOG.error("查询单个订单失败", e);
                return new Result(false, new ProductionOrder());
            }
        }

        @SysLog(action = "update", value = "修改订单")
        @ApiOperation(value = "修改订单")
        @PutMapping("/update")
        public Result update(@Valid @RequestBody final ProductionOrder entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "修改订单失败", errorMsg, map);
                } else {
                    if (null == entity.getOrderId()) {
                         throw new RuntimeException("id不能为空");
                    }
                    entityService.updateById(entity);
                    return new Result(true, "成功修改订单", null);
                }
            } catch (Exception e) {
                LOG.error("修改订单失败", e);
                return new Result(false, "修改订单失败", e.getMessage());
            }
        }

        @SysLog(action = "all", value = "查询全部订单")
        @ApiOperation(value = "全部订单")
        @GetMapping("/all")
        public Result<List<ProductionOrder>> all(ProductionOrder example) {
            List<ProductionOrder> entitys = entityService.list(example);
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }
        //正在执行的订单列表
        @SysLog(action = "running", value = "查询执行中的订单")
        @ApiOperation(value = "正在执行的订单列表")
        @GetMapping("/running")
        public Result<List<ProductionOrder>> running() {
            List<ProductionOrder> entitys = entityService.running();
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }
        //获取空闲订单列表

    @SysLog(action = "free", value = "查询空闲订单")
        @ApiOperation(value = "获取空闲订单列表")
        @GetMapping("/free")
        public Result<List<ProductionOrder>> free() {
            List<ProductionOrder> entitys = entityService.list(new QueryWrapper<ProductionOrder>().eq("status","待排产"));
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }
    @SysLog(action = "complete", value = "完成订单")
        @ApiOperation(value = "完成订单")
        @PostMapping("/complete")
        public Result complete(@RequestParam Integer id) {
            try {
                return new Result<>(true, entityService.complete(id));
            } catch (Exception e) {
                LOG.error("完成订单失败", e);
                return new Result<>(false, "完成订单失败", e.getMessage());
            }
        }

    @SysLog(action = "addToProduction", value = "分配订单到生产线")
        @ApiOperation(value = "订单（选择合适的生产线）加入生产")
        @PostMapping("/addToProduction")
        public Result addToProduction(Integer id,Integer productionLineId) {
            try {
                entityService.addToProduction(id,productionLineId);
                return new Result<>(true,"订单加入生产成功");
            } catch (noEquitmentException e) {
                LOG.error(e.getMessage(), e);
                return new Result<>(false, e.getMessage(), e.getMessage());
            }
            catch (Exception e) {
                LOG.error("将订单加入生产失败", e);
                return new Result<>(false, "将订单加入生产失败", e.getMessage());
            }
        }
        //将订单移出生产线（停止某订单）
        @SysLog(action = "removeFromLine", value = "从生产线移除订单")
        @ApiOperation(value = "将订单移出当前执行的生产线")
        @PostMapping("/removeFromLine")
        public Result removeFromLine(@RequestParam Integer id) {
            try {
                return new Result<>(true, entityService.removeFromLine(id));
            } catch (Exception e) {
                LOG.error("将订单移出当前执行的生产线失败", e);
                return new Result<>(false, "将订单移出当前执行的生产线失败", e.getMessage());
            }
        }

        //将订单priority优先级设置为紧急
        @SysLog(action = "setPriorityUrgent", value = "设置紧急优先级")
        @ApiOperation(value = "将订单优先级设置为紧急")
        @PostMapping("/setPriorityUrgent")
        public Result setPriorityUrgent(@RequestParam Integer id) {
            try {
                return new Result<>(true, entityService.setPriorityUrgent(id));
            } catch (Exception e) {
                LOG.error("将订单优先级设置为紧急失败", e);
                return new Result<>(false, "将订单优先级设置为紧急失败", e.getMessage());
            }
        }
        //取消订单priority优先级设置为紧急

    @SysLog(action = "cancelPriorityUrgent", value = "取消紧急优先级")
        @ApiOperation(value = "将订单取消加急")
        @PostMapping("/cancelPriorityUrgent")
        public Result cancelPriorityUrgent(@RequestParam Integer id) {
            try {
                return new Result<>(true, entityService.cancelPriorityUrgent(id));
            } catch (Exception e) {
                LOG.error("将订单取消加急失败", e);
                return new Result<>(false, "将订单取消加急失败", e.getMessage());
            }
        }
        //获取待排产的订单
        @SysLog(action = "getWaitingOrders", value = "查询待排产订单")
    @ApiOperation(value = "获取待排产的订单")
    @GetMapping("/getWaitingOrders")
    public Result<List<ProductionOrder>> getWaitingOrders() {
        List<ProductionOrder> entitys = entityService.getWaitingOrders();
        if (null != entitys) {
            return new Result<>(true, entitys);
        }
        return new Result<>(true, Collections.emptyList());
    }
    //搜索订单
    @SysLog(action = "search", value = "复合条件搜索订单")
    @ApiOperation(value = "搜索订单")
    @GetMapping("/search")
    public Result<Page<ProductionOrder>> searchAnd(@RequestParam(required = false) String key,
                                               @RequestParam(required = false) String status, final Page page){
        try {
            LambdaQueryWrapper<ProductionOrder> wrapper = new LambdaQueryWrapper<>();
            if (StringUtil.isNotBlank(key)) {
                wrapper.and(q ->
                        q.eq(ProductionOrder::getProductModel, key)
                                .or()
                                .eq(ProductionOrder::getCustomer, key)
                );
            }
            wrapper.eq(StringUtil.isNotBlank(status), ProductionOrder::getStatus, status);
            Page<ProductionOrder> entitys = entityService.page(page, wrapper);
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true);
        } catch (Exception e) {
            LOG.error("设备名搜索失败", e);
            return new Result<>(false, "设备名搜索失败", e.getMessage());
        }
    }
    //新增订单
    @SysLog(action = "add", value = "创建新订单")
    @ApiOperation(value = "添加订单")
    @PostMapping("/add")
    public Result add(@Valid @RequestBody final ProductionOrder entity, final BindingResult result) {
        try {
            if (result.hasErrors()) {
                Map<String, String> map = this.getErrors(result);
                String errorMsg = map.entrySet().iterator().next().getValue();
                return new Result(false, "保存工序区失败", errorMsg, map);
            } else {
                entity.setBegintime(LocalDateTime.now())
                        .setPriority("0")
                        .setOrderId(null)
                        .setOrderBylineId( null)
                        .setCreatedAt(LocalDateTime.now())
                        .setUpdatedAt(LocalDateTime.now())
                        .setCount(0)
                        .setLowcount(0)
                ;
                entityService.save(entity);
                return new Result(true, "成功保存工序区", null);
            }
        } catch (Exception e) {
            LOG.error("添加工序区失败", e);
            return new Result(false, "保存工序区失败", e.getMessage());
        }
    }
}

